package com.collection.web.controller.sys;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.collection.api.entity.sys.SysUser;
import com.collection.api.sys.SysRoleService;
import com.collection.api.sys.SysUserService;
import com.collection.web.pagination.Page;
import com.collection.web.pagination.PageBuilder;
import com.collection.web.pagination.PageRequest;
import com.collection.web.resolver.annotation.GridParam;
 


/**
 * 系统用户管理
 *
 */
@Controller
@RequestMapping("/user")
public class SysUserController {
	private static final Logger  logger  = LoggerFactory.getLogger(SysUserController.class);
	
	@Reference(version="1.0.0")
	private SysUserService sysUserService;
	
	@Reference(version="1.0.0")
	private SysRoleService sysRoleService;
	
	private String errorCode = "";
	private String errorMessage="";
	Map<String,Object> map = new HashMap<String,Object>();
	
	/**
	 * 链接到用户管理列表页面
	 * @return
	 */
	@RequestMapping(value="index")
	public String index(String userName,String realName,String mobile,String userType,@GridParam PageRequest pageRequest,HttpServletRequest request){
		logger.info("---------------进入用户管理列表接口-------------------");
		List<Map<String, Object>> list = sysUserService.findUserList(userName, realName, mobile, userType, pageRequest.getOffset(), pageRequest.getPageSize());
		int total = sysUserService.countUserList(userName, realName, mobile, userType);
		Page<Map<String, Object>> page = PageBuilder.buildPage(pageRequest, list, total);
		request.setAttribute("total",page.getTotalPages());
		request.setAttribute("page", page);
		request.setAttribute("userName", userName);
		request.setAttribute("realName", realName);
		request.setAttribute("mobile", mobile);
		request.setAttribute("userType", userType);
		logger.info("---------------list-------------------"+page.getTotal());
		return "sys/user/list";
	}
	
	/**
	 * 查询列表
	 * @return
	 */
	public Page<Map<String, Object>> list(String userName,String realName,String mobile,String userType,@GridParam PageRequest pageRequest,HttpServletRequest request) {
		List<Map<String, Object>> list = sysUserService.findUserList(userName, realName, mobile, userType, pageRequest.getOffset(), pageRequest.getPageSize());
		int total = sysUserService.countUserList(userName, realName, mobile, userType);
		Page<Map<String, Object>> page = PageBuilder.buildPage(pageRequest, list, total);
		request.setAttribute("page", page);
		return page;
	}
	
	
	
	/**
	 * 进入添加界面
	 */
	@RequestMapping("/add")
	public String add(HttpServletRequest request) {
		logger.info("---------------进入增加用户接口-------------------");
		List<Map<String, Object>> roleList = sysRoleService.findRoleList(null, null, null, null);
		logger.info("---------------用户角色数量-------------------"+roleList.size());
		request.setAttribute("roleList", roleList);
		return "sys/user/add";
	}
	/**
	 * 添加操作，保存数据
	 * 
	 * @return
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(SysUser sysUser,HttpServletRequest request,@GridParam PageRequest pageRequest) {
		try {
			logger.info("---------------增加用户-------------------");
			String userName = sysUser.getUserName();
			SysUser mUser = sysUserService.findByUsername(userName);
			if(mUser!= null){
				errorCode = "1";
				errorMessage = "用户名已存在!";
				request.setAttribute("user", sysUser);
				request.setAttribute("errorCode", errorCode);
				request.setAttribute("errorMessage", errorMessage);
				List<Map<String, Object>> roleList = sysRoleService.findRoleList(null, null, null, null);
				request.setAttribute("roleList", roleList);
				return "sys/user/add";
			}else{
				int uSize = sysUserService.countUserByMobile(sysUser.getMobile());
				if(uSize > 0){
					errorCode = "1";
					errorMessage = "联系电话已存在!";
					request.setAttribute("user", sysUser);
					request.setAttribute("errorCode", errorCode);
					request.setAttribute("errorMessage", errorMessage);
					List<Map<String, Object>> roleList = sysRoleService.findRoleList(null, null, null, null);
					request.setAttribute("roleList", roleList);
					return "sys/user/add";
				}else{
					sysUser.setPassword(encryptPwd(sysUser.getPassword()));
					sysUser.setLocked(sysUser.getLocked());
					sysUser.setCreateTime(new Date());
					sysUser.setType("");
					int id = sysUserService.insertSelective(sysUser);
					if(id>0){
						errorCode = "0";
						errorMessage = "保存成功!";
					}else{
						errorCode = "1";
						errorMessage = "保存失败!";
					}
				}
			}
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			int total = 0;
			if(StringUtils.isNoneBlank(errorCode) && !"".equals(errorCode) && "0".equals(errorCode)){
				list = sysUserService.findUserList(userName, sysUser.getRealName(), sysUser.getMobile(), null, pageRequest.getOffset(), pageRequest.getPageSize());
				total = sysUserService.countUserList(userName, sysUser.getRealName(), sysUser.getMobile(), null);
				request.setAttribute("userName", userName);
				request.setAttribute("realName", sysUser.getRealName());
				request.setAttribute("mobile", sysUser.getMobile());
			}else{
				list = sysUserService.findUserList(null, null, null, null, pageRequest.getOffset(), pageRequest.getPageSize());
				total = sysUserService.countUserList(null, null, null, null);
			}
			Page<Map<String, Object>> page = PageBuilder.buildPage(pageRequest, list, total);
			request.setAttribute("page", page);
			
		} catch (Exception e) {
			logger.info("增加用户异常Exception:"+e.getMessage());
			e.printStackTrace();
			errorCode = "1";
			errorMessage = "保存异常!";
		}
		request.setAttribute("errorCode", errorCode);
		request.setAttribute("errorMessage", errorMessage);
		return "sys/user/list";
	}
	
	/**
	 * 进入修改界面
	 */
	@RequestMapping("/edit")
	public String edit(Integer id, HttpServletRequest request) {
		logger.info("---------------进入修改用户接口-------------------");
		SysUser sysUser = sysUserService.selectByPrimaryKey(id);
		List<Map<String, Object>> roleList = sysRoleService.findRoleList(null, null, null, null);
		logger.info("---------------用户角色数量-------------------"+roleList.size());
		request.setAttribute("roleList", roleList);
		request.setAttribute("user", sysUser);
		return "sys/user/edit";
	}
	/**
	 * 保存修改数据
	 * @param SysUser
	 * @return
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update(SysUser sysUser,HttpServletRequest request,@GridParam PageRequest pageRequest) {
		logger.info("---------------修改用户信息-------------------");
		try {
			
			SysUser user = sysUserService.selectByPrimaryKey(sysUser.getId());
			if (user == null) {
				errorCode = "1";
				errorMessage = "用户不存在!";
				request.setAttribute("user", sysUser);
				request.setAttribute("errorCode", errorCode);
				request.setAttribute("errorMessage", errorMessage);
				List<Map<String, Object>> roleList = sysRoleService.findRoleList(null, null, null, null);
				request.setAttribute("roleList", roleList);
				return "sys/user/edit";
			}else{
				
				boolean isExistsUserName = false;
				if(! (sysUser.getUserName().equals(user.getUserName()))) {
					isExistsUserName = true;
				}
				
				if(isExistsUserName) {
					SysUser mUser = sysUserService.findByUsername(sysUser.getUserName());
					if(mUser!= null){
						errorCode = "1";
						errorMessage = "用户名已存在!";
						request.setAttribute("user", sysUser);
						request.setAttribute("errorCode", errorCode);
						request.setAttribute("errorMessage", errorMessage);
						List<Map<String, Object>> roleList = sysRoleService.findRoleList(null, null, null, null);
						request.setAttribute("roleList", roleList);
						return "sys/user/edit";
					}
				}
				
				boolean isExistsMobile = false;
				if((user.getMobile() !=null )&& ! ( user.getMobile().equals(sysUser.getMobile()))) {
					isExistsMobile = true;
				}
			 
				if(isExistsMobile) {
				 
					int uSize = sysUserService.countUserByMobile(sysUser.getMobile());
					if (uSize > 0) {
						errorCode = "1";
						errorMessage = "联系电话已存在!";
						request.setAttribute("user", sysUser);
						request.setAttribute("errorCode", errorCode);
						request.setAttribute("errorMessage", errorMessage);
						List<Map<String, Object>> roleList = sysRoleService.findRoleList(null, null, null, null);
						request.setAttribute("roleList", roleList);
						return "sys/user/edit";
					}
				} 
				
				sysUser.setCreateTime(new Date());
				sysUser.setPassword(encryptPwd(user.getPassword()));
				int id = sysUserService.updateByPrimaryKeySelective(sysUser);
				if(id>0){
					errorCode = "0";
					errorMessage = "更新用户成功!";
				}else{
					errorCode = "1";
					errorMessage = "更新用户失败!";
				}
			}
		 
	 
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			int total = 0;
			if(StringUtils.isNoneBlank(errorCode) && !"".equals(errorCode) && "0".equals(errorCode)){
				list = sysUserService.findUserList(sysUser.getUserName(), sysUser.getRealName(), sysUser.getMobile(), null, pageRequest.getOffset(), pageRequest.getPageSize());
				total = sysUserService.countUserList(sysUser.getUserName(), sysUser.getRealName(), sysUser.getMobile(), null);
				request.setAttribute("userName", sysUser.getUserName());
				request.setAttribute("realName", sysUser.getRealName());
				request.setAttribute("mobile", sysUser.getMobile());
			}else{
				list = sysUserService.findUserList(null, null, null, null, pageRequest.getOffset(), pageRequest.getPageSize());
				total = sysUserService.countUserList(null, null, null, null);
			}
			Page<Map<String, Object>> page = PageBuilder.buildPage(pageRequest, list, total);
			request.setAttribute("page", page);
		} catch (Exception e) {
			logger.info("修改用户异常Exception:"+e.getMessage());
			e.printStackTrace();
			errorCode = "1";
			errorMessage = "更新用户失败!";
		}
		request.setAttribute("errorCode", errorCode);
		request.setAttribute("errorMessage", errorMessage);
		return "sys/user/list";
	}
	
   private String encryptPwd(String pwd) {
        return new SimpleHash("MD5", pwd).toHex();
    }
	   
	
	/**
	 * 删除用户
	 * @param userName
	 * @return
	 */
	@RequestMapping(value = "/delete")
	public String delete(Integer id,HttpServletRequest request,@GridParam PageRequest pageRequest) {
		logger.info("---------------锁定用户信息-------------------");
		try {
			int resultId = sysUserService.lockedUser(id);
			if(resultId>0){
				errorCode = "0";
				errorMessage = "锁定成功!";
			}else{
				errorCode = "1";
				errorMessage = "锁定失败!";
			}
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			int total = 0;
			list = sysUserService.findUserList(null, null, null, null, pageRequest.getOffset(), pageRequest.getPageSize());
			total = sysUserService.countUserList(null, null, null, null);
			Page<Map<String, Object>> page = PageBuilder.buildPage(pageRequest, list, total);
			request.setAttribute("page", page);
		} catch (Exception e) {
			logger.info("锁定用户异常Exception:"+e.getMessage());
			e.printStackTrace();
			errorCode = "1";
			errorMessage = "锁定异常!";
		}
		request.setAttribute("errorCode", errorCode);
		request.setAttribute("errorMessage", errorMessage);
		return "sys/user/list";
	}
	
	/**
	 * 解锁用户
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/open")
    public Object open(Integer id,HttpServletRequest request,@GridParam PageRequest pageRequest) {
		logger.info("---------------解锁用户信息-------------------");
        try {
        	int resultId =  sysUserService.openUser(id);
        	if(resultId>0){
				errorCode = "0";
				errorMessage = "解锁成功!";
			}else{
				errorCode = "1";
				errorMessage = "解锁失败!";
			}
        	List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			int total = 0;
			list = sysUserService.findUserList(null, null, null, null, pageRequest.getOffset(), pageRequest.getPageSize());
			total = sysUserService.countUserList(null, null, null, null);
			Page<Map<String, Object>> page = PageBuilder.buildPage(pageRequest, list, total);
			request.setAttribute("page", page);
        } catch (Exception e) {
        	logger.info("解锁用户信息异常Exception:"+e.getMessage());
            e.printStackTrace();
            errorCode = "1";
			errorMessage = "解锁异常!";
        }
        request.setAttribute("errorCode", errorCode);
		request.setAttribute("errorMessage", errorMessage);
		return "sys/user/list";
    }
	
	/**
	 * 进入修改密码页面
	 */
	 @RequestMapping("/updatePwd")
	    public String updatePwd(){
	        return "sys/user/updatePwd";
	    }
	 
	 /**
	  * 查询所有用户
	  */
	 @RequestMapping(value = "/findAllUserInfo")
	 @ResponseBody
	 	public List<SysUser> findAllUserInfo() {
		 return sysUserService.getUserByParam(null, null, null, null, null, null, null);
	 }
	 
	 /**
		 * 链接到用户管理列表页面
		 * @return
		 */
		@RequestMapping("/welcome")
		public String welcome(){
			return "welcome";
		}

	public String getErrorCode() {
		return errorCode;
	}

	public void setErrorCode(String errorCode) {
		this.errorCode = errorCode;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}
	 
		
	
}
